package com.bigevent.bigevent.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author yangxudong
 * @description: 用户工具类
 * @date 2024/2/3 21:56
 */
public class UserUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(UserUtil.class);
    public static String getUsername() {
        Map<String, Object> userMap = getUesrMap();
        if (userMap == null) return null;
        // 返回local变量中的username
        return (String) userMap.get("username");
    }

    private static Map<String, Object> getUesrMap() {
        // 获取当前线程的local变量
        Map<String, Object> userMap = ThreadLocalUtil.get();
        // 如果local变量为空
        if (CollectionUtils.isEmpty(userMap)) {
            LOGGER.error("当前threadlocal中不存在用户信息");
            return null;
        }
        return userMap;
    }

    public static Integer getUserId() {
        Map<String, Object> userMap = getUesrMap();
        if (userMap == null) return null;
        // 返回local变量中的userid
        return (Integer) userMap.get("userId");
    }
}
